package com.fengxu.gamescript.ui.setting

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.Conf
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.data.UserType
import com.fengxu.gamescript.data.po.User
import com.fengxu.gamescript.provide.ProviderFactory
import com.fengxu.gamescript.service.AutoAccessibilityService
import com.fengxu.gamescript.ui.about.AboutActivity
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.ui.cloud.CloudMusicActivity
import com.fengxu.gamescript.util.CommonUtils
import com.fengxu.gamescript.util.PermissionUtils
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.utils.Utils
import com.xuexiang.xui.widget.button.switchbutton.SwitchButton
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.joda.time.DateTime


/**
 * 设置页弹出框
 */
class SettingDialog: Dialog {

    /**
     * 悬浮窗状态改变事件
     */
    val onFlowWinChanged: ((Boolean) -> Unit)? = null


    constructor(ctx: Context):super(ctx){
        setContentView(R.layout.dialog_setting)
        var width = (Utils.getScreenWidth(ctx) * 0.8).toInt()
        window?.run {
            setGravity(Gravity.LEFT)
            setLayout(width, WindowManager.LayoutParams.MATCH_PARENT)
            decorView.setBackgroundResource(R.color.white)
            decorView.padding = 0
            setWindowAnimations(R.style.dialog_anim)
        }
        try {
            initView()
        }catch (e:java.lang.Exception){
            BaseActivity.exitAll()
        }
    }

    /**
     * 显示时更新信息
     */
    override fun show() {
        initView()
        super.show()
    }

    /**
     * 初始化控件
     */
    private fun initView(){
        // 初始化用户信息
        findViewById<TextView>(R.id.setting_userType).text = UserType.valueOf(GlobalData.user!!.role).typeName
        findViewById<TextView>(R.id.setting_email).text = GlobalData.user!!.email
        var expire = DateTime(GlobalData.user!!.expire).toString("yyyy-MM-dd HH:mm:ss")
        findViewById<TextView>(R.id.setting_expire).text = expire
        findViewById<TextView>(R.id.setting_remainTimes).text = GlobalData.user!!.remainTimes.toString()
        // 设置下拉刷新用户信息
        findViewById<SmartRefreshLayout>(R.id.setting_smartRefresh).setOnRefreshListener{refreshUserInfo(
            it as SmartRefreshLayout
        )}
        /*************  初始化设置信息 **************/
        // 获取屏幕分辨率
        findViewById<View>(R.id.setting_metric).onClick {
            val displayMetrics = DensityUtils.getScreenMetrics(true)
            CommonUtils.toastDialog(context, title = "您当前分辨率为:",
                    content = "${displayMetrics.heightPixels} x ${displayMetrics.widthPixels}")
        }
        // 加群
        findViewById<View>(R.id.setting_addGroup).onClick { joinQQGroup() }
        // 打开云音乐脚本下载界面
        findViewById<View>(R.id.setting_downMusicScript).onClick {
            context.startActivity(Intent(context, CloudMusicActivity::class.java))
            dismiss()
        }
        // 打开键位设置页
        findViewById<View>(R.id.setting_startYsSetting).onClick {
            context.startActivity(Intent(context, KeyConfActivity::class.java))
            dismiss()
        }
        // 悬浮窗
        initFlowWin()
        // 无障碍
        initAccessibility()
        // 关于
        findViewById<TextView>(R.id.setting_about).onClick {
            context.startActivity(Intent(context, AboutActivity::class.java))
            dismiss()
        }
        // 退出
        findViewById<TextView>(R.id.setting_exit).onClick { BaseActivity.exitAll() }

    }


    /**
     * 从指定布局中获取switch开关(开关设置了tag="switch")
     */
    private fun findSwitchByView(view: View): SwitchButton{
       return view.findViewWithTag<SwitchButton>("switch")
    }

    /**
     * 加入QQ群
     */
    @SuppressLint("WrongConstant")
    private fun joinQQGroup() {
        val intent = Intent()
        intent.data =
            Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3DxkfUekCTPioEWt6Ll5utD5H3Er-sOohK")
        try {
            context.startActivity(intent)
        } catch (e: Exception) {
            Toast.makeText(context, "您未安装手机QQ", 3000).show()
        }
    }

    /**
     * 初始化悬浮窗信息配置
     */
    private fun initFlowWin(){
        val flowWin = findViewById<View>(R.id.setting_startFlowWin)
        val switch = findSwitchByView(flowWin)
        switch.isChecked = Conf.getConf().isStartFlowWin
        flowWin.onClick {
            if(!Conf.getConf().isStartFlowWin){
                // 检查权限，准备开启
                if(!PermissionUtils.checkFloatPermission(context)){
                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                    intent.data = Uri.parse("package:" + context.packageName)
                    context.startActivity(intent)
                }else{
                    // 已有权限直接开启
                    onFlowWinChanged?.invoke(true)
                    Conf.getConf().isStartFlowWin = true
                    Conf.saveConf(context)
                    switch.isChecked = true
                }
            }else{
                // 关闭悬浮窗
                onFlowWinChanged?.invoke(false)
                Conf.getConf().isStartFlowWin = false
                Conf.saveConf(context)
                switch.isChecked = false
            }
        }
    }

    /**
     * 初始化无障碍服务
     */
    private fun initAccessibility() {
        var layout = findViewById<LinearLayout>(R.id.setting_startAccessibility)
        var switch = findSwitchByView(layout)
        switch.isChecked = AutoAccessibilityService.serviceIsRunning()
        layout.onClick {
            if(switch.isChecked){
                AutoAccessibilityService.accessibilityService?.disableSelf()
                switch.isChecked = false
            }else{
                context.startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
            }
            dismiss()
        }
    }

    /**
     * 刷新用户信息
     */
    private fun refreshUserInfo(layout: SmartRefreshLayout){
        doAsync {
            val result = ProviderFactory.dataProvider.userInfo
            if(result == null){
                context.runOnUiThread {
                    XToast.error(context, "网络连接失败,请检查您的网络!").show()
                    layout.finishRefresh()
                }
                return@doAsync
            }
            when(result.code){
                200 -> {
                    GlobalData.user = JSONObject.parseObject(result.data.toString(), User::class.java)
                    context.runOnUiThread { initView() }
                }
                else -> {
                    context.runOnUiThread { CommonUtils.toastDialog(context, content = result.msg) }
                }
            }
            context.runOnUiThread { layout.finishRefresh() }
        }
    }

}